package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import com.estore.service.ProductSorters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Comparator;
import java.util.List;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    showSortedProducts();
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    checkout(); // 结算功能
                    break;
                case 6:
                    new AdminConsole().start(); // 管理员入口
                    break;
                case 7:
                    // 退出逻辑
                    if (productService.saveData()) {
                        System.out.println("数据已保存，感谢使用，再见！");
                    } else {
                        System.out.println("数据保存失败，请稍后重试！");
                    }
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }

    }
    private void backupData() {
        System.out.println("\n--- 数据备份功能 ---");
        String sourcePath = productService.getDataFilePath(); // 获取源文件路径
        String backupPath = sourcePath + ".bak"; // 备份文件路径（如products.dat.bak）

        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            System.out.println("源数据文件不存在，无法备份！");
            return;
        }

        // 字节流+缓冲区读写（1024字节=1KB缓冲区）
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupPath)) {

            byte[] buffer = new byte[1024];
            int readLen; // 每次实际读取的字节数
            long totalBytes = 0; // 总备份字节数

            // 循环读写：读取到缓冲区→写入备份文件
            while ((readLen = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLen); // 只写实际读取的字节（避免缓冲区残留）
                totalBytes += readLen;
            }

            System.out.println("备份成功！");
            System.out.println("源文件：" + sourcePath);
            System.out.println("备份文件：" + backupPath);
            System.out.println("备份大小：" + totalBytes + " 字节");

        } catch (IOException e) {
            System.err.println("备份失败！");
            e.printStackTrace();
        }
    }
    private void showMenu() {
        System.out.println("\n 欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("5. 结算购买"); // 新增结算选项
        System.out.println("6. 管理员入口"); // 新增管理员入口
        System.out.println("7. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void showSortedProducts() {
        System.out.println("\n--- 请选择排序方式 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.print("请输入排序方式编号: ");
        int sortChoice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        // 根据选择获取对应的Comparator
        switch (sortChoice) {
            case 1:
                browseProducts(ProductSorters.BY_PRICE_ASC);
                break;
            case 2:
                browseProducts(ProductSorters.BY_PRICE_DESC);
                break;
            case 3:
                browseProducts(ProductSorters.BY_STOCK_DESC);
                break;
            default:
                System.out.println("无效的排序选择，将使用默认排序（按ID升序）");
                browseProducts(null);
        }
    }
    private void browseProducts(Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts(); // 新建列表避免修改原集合
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        // 按传入的Comparator排序：有则用自定义规则，无则用默认排序（Comparable）
        if (comparator != null) {
            products.sort(comparator);
        } else {
            Collections.sort(products);
        }

        // 打印排序后的商品
        products.forEach(System.out::println);
    }
//    private static void getPrintln() {
//        System.out.println("3. 添加商品到购物车");
//    }

    private void browseProducts() {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            products.forEach(System.out::println);
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }
    // 结算功能
    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车为空，无法结算");
            return;
        }

        System.out.println("\n--- 结算确认 ---");
        viewCart(); // 显示购物车内容

        System.out.print("确认结算？(y/n): ");
        String confirm = scanner.nextLine();
        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("已取消结算");
            return;
        }

        // 检查库存
        boolean canCheckout = true;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            if (product.getStock() < entry.getValue()) {
                System.out.println("商品 " + product.getName() + " 库存不足，当前库存: " + product.getStock());
                canCheckout = false;
            }
        }

        if (!canCheckout) {
            System.out.println("结算失败，请调整购物车");
            return;
        }

        // 扣减库存
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            product.setStock(product.getStock() - entry.getValue());
        }

        System.out.println("结算成功！感谢您的购买");
        shoppingCart.clear();
        productService.saveData(); // 保存库存变更
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}